package com.jiangxiaofei.citycloud.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.adapter.MainMenuGridViewAdapter;
import com.jiangxiaofei.citycloud.bean.HomeMenuItemBean;
import com.jiangxiaofei.citycloud.bean.JsonBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.util.BannerImageLoder;
import com.jiangxiaofei.citycloud.util.GetJsonDataUtil;
import com.jiangxiaofei.citycloud.view.SlidingGridView;
import com.youth.banner.Banner;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by JiangXFei on 2017/8/9.
 */

public class MainFragment extends Fragment {

    @InjectView(R.id.home_header_banner)
    Banner homeHeaderBanner;
    @InjectView(R.id.home_tv_header_city)
    TextView homeTvHeaderCity;
    @InjectView(R.id.home_et_header_search)
    TextView homeEtHeaderSearch;
    @InjectView(R.id.home_frag_scv)
    ScrollView homeFragScv;
    @InjectView(R.id.main_gv_menu)
    SlidingGridView mainGvMenu;
    private View homeView;

    private List<Integer> imgList = new ArrayList<>();
    private int[] menuImgs = new int[]{R.drawable.ic_csmy
//            , R.drawable.ic_ggjz
            , R.drawable.ic_cstc
//            , R.drawable.ic_dxzq
            , R.drawable.ic_csjs
            , R.drawable.ic_mlxc
//            , R.drawable.ic_cssp
//            , R.drawable.ic_csmy
    };
    //地点选择
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private Thread thread;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;

            }
        }
    };
    private List<HomeMenuItemBean> menuList;
    private MainMenuGridViewAdapter menuAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        homeView = inflater.inflate(R.layout.fragment_main_layout, null);
        ButterKnife.inject(this, homeView);
        initDate();
        init(imgList);
        if (Constants.bdLocation != null) {
            homeTvHeaderCity.setText(Constants.bdLocation.getCity());
        } else {
            homeTvHeaderCity.setText("青岛");
        }
        return homeView;
    }

    /**
     * 测试banner轮播图   以及导航栏
     */
    private void initDate() {
        imgList.clear();
        imgList.add(R.drawable.slide1);
        imgList.add(R.drawable.slide2);
        imgList.add(R.drawable.slide3);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        String[] stringArray = getResources().getStringArray(R.array.home_menu);
        menuList = new ArrayList<>();
        for (int i = 0; i < stringArray.length; i++) {
            HomeMenuItemBean menuItemBean = new HomeMenuItemBean();
            menuItemBean.setName(stringArray[i]);
            menuItemBean.setResource(menuImgs[i]);
            menuList.add(menuItemBean);
        }
        menuAdapter = new MainMenuGridViewAdapter(menuList, getActivity());
        mainGvMenu.setAdapter(menuAdapter);
    }

    private void init(List<Integer> imgList) {
        homeHeaderBanner.setImageLoader(new BannerImageLoder());
        homeHeaderBanner.setImages(imgList);
        homeHeaderBanner.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @OnClick({R.id.home_tv_header_city})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.home_tv_header_city:
                ShowPickerView(homeTvHeaderCity);
                break;
            default:
                break;
        }
    }

    /**
     * 开始加载地址选择器  start
     */
    private void ShowPickerView(final TextView tv) {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
//                String tx = options1Items.get(options1).getPickerViewText() +
//                        options2Items.get(options1).get(options2) +
//                        options3Items.get(options1).get(options2).get(options3);
                String tx = options2Items.get(options1).get(options2);
                Constants.positions.clear();
                Constants.positions = options3Items.get(options1).get(options2);
                tv.setText(tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

//   pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
//        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(getActivity(), "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);
                        if (Constants.bdLocation != null && CityName.equals(Constants.bdLocation.getCity())) {
                            Constants.positions.add(AreaName);
                        }
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
    /**
     * 开始加载地址选择器  end
     */
}
